package com.geek.aspect;

import com.geek.annotation.DataSource;
import com.geek.config.DynamicDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 切面配置
 */
@Aspect
@Component
public class DataSourceAspect {


    @Pointcut("@annotation(com.geek.annotation.DataSource)")
    public void dataSourcePointCut() {

    }

    /**
     * 环绕通知
     */
    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource ds = method.getAnnotation(DataSource.class);
        if (ds == null) {
            // 默认主库
            DynamicDataSource.setDataSource("write");
            System.out.println("set datasource is " + "write");
        } else {
            DynamicDataSource.setDataSource(ds.name());
            System.out.println("set datasource is " + ds.name());
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }
}
